<template>
    <!-- 饼状图 -->
    <div>
      <div class="query-wrap">
        <el-checkbox
          v-model="queryParmas.queryQcTask"
          label="品控关注"
          border
          size="small"
          class="related-me"
          true-label="1"
          :false-label="null"
          @change='getTasklList'
        ></el-checkbox>
        <el-select
          v-model="queryParmas.taskType"
          placeholder="请选择任务类型"
          clearable
          size="small"
          @change="getTasklList"
        >
          <el-option
            v-for="item in dict.taskType"
            :key="item.codevalue"
            :label="item.codename"
            :value="item.codevalue"
          >
          </el-option>
        </el-select>

        <div class="button-wrap">
          <el-button size="mini" :type="activeName == 1 ? 'primary' : ''" @click='changeTab("1")'>今日</el-button>
          <el-button size="mini" :type="activeName == 7 ? 'primary' : ''" @click='changeTab("7")' class="seven">近七日</el-button>
        </div>
      </div>

      <div class="chart-wrap">
        <div ref="taskChart" class="chart-content" style="{height: 200px;}"></div>
      </div>
    </div>
</template>
<script>
  import {getTaskSummary} from "@/api/workbench/index";
  import {getTaskOption } from '../echartOption'
  import { mapMutations } from "vuex";
export default {
  props:{
    filterData:{
      type:Object,
      default:()=>{}
    }
  },
  dicts: ["taskType", "taskStatus"],
  data() {
    return {
      activeName:"1",
      queryParmas:{
        ownedFactory:null,
        ownedWorkshop:null,
        ownedProductionLine:null,
        lineId:null,
        taskType:null,
        queryQcTask:null,
        day:"1"
      },
      loading: false,
      taskTotal:0,
      rateComplete:0,
      completeTotal:0,
      echartsInstance: null,
      chartData:[],
      refreshTimer:null
    };
  },

  created() {
  },

  computed: {
  },

  methods:{
    ...mapMutations("workbench", ["SET_TASKANALYSIS_DETAIL","SET_TASKHIS_DETAIL"]),
    setRefreshTimer(){
      if (this.refreshTimer) {
        clearTimeout(this.refreshTimer);
        if(this.echartsInstance){
          this.echartsInstance.off('legendselectchanged');
        }
      }
      this.echartsInstance = null;
      this.refreshTimer = setTimeout(() => {
        this.getTasklList();
        this.setRefreshTimer();
      },60000)
    },
    getTasklList(){
      this.taskTotal = 0;
      this.rateComplete = 0;
      let tableData = []
      getTaskSummary(this.queryParmas)
      .then((res) => {
        tableData = [];
        this.chartData = [];
        if(res.code == 200 && res.data){
          tableData = res.data;
          this.$nextTick(()=>{
            if(tableData?.length){
              tableData.map(ele => {
                this.chartData.push({
                  value:ele?.count ? Number(ele.count) : 0,
                  name:ele.statusName
                })
                this.taskTotal += ele.count;
                if(ele.status == 4){//已完成
                  this.completeTotal = ele?.count || 0;
                }
              })
              if(this.taskTotal){
                this.rateComplete = ((this.completeTotal/this.taskTotal)*100).toFixed(2) > 0 ? ((this.completeTotal/this.taskTotal)*100).toFixed(2)+"%" : 0
              }
              else{
                this.taskTotal = 0;
                this.rateComplete = 0;
              }
              this.initChart()
            }
          })
        }
        else{
          tableData = [];
          this.chartData = []
          this.taskTotal = 0;
          this.rateComplete = 0;
        }
      })
      .catch(() => {
        tableData = [];
        this.chartData = []
        this.taskTotal = 0;
        this.rateComplete = 0;
      });
    },

    initChart(){
      this.echartsInstance = null;
      // 基于准备好的dom，初始化echarts实例
      this.echartsInstance = this.$echarts.init(this.$refs.taskChart, null, {renderer:'svg'})

      // 指定图表的配置项和数据
      const option = getTaskOption(this.chartData,this.taskTotal,this.rateComplete )

      // 使用刚指定的配置项和数据显示图表。
      this.echartsInstance.setOption(option);
      if(this.echartsInstance){
        this.echartsInstance.off('legendselectchanged');
      }
      this.echartsInstance.on('legendselectchanged', (params)=> {
        const {ownedFactory,ownedWorkshop,ownedProductionLine,lineId,taskType,queryQcTask,day} = this.queryParmas;
        let time = [];
        if(this.queryParmas.day == "1"){//今日
          time = this.toTeamTimeSep(1);
        }else{
          time = this.toTeamTimeSep(7);
        }
        const status = this.dict.taskStatus?.length && this.dict.taskStatus.find(ele => ele.codename === params.name)?.codevalue
        let path ="./"
        if(status == "6" || status == "4"){//已完成,已关闭
          this.SET_TASKHIS_DETAIL({
            factoryDeptCode:ownedFactory,
            workshopCode:ownedWorkshop,
            lineCode:ownedProductionLine,
            lineId,
            queryType:"workshop",
            queryQcTask,
            taskType,
            status,
            time:time
          })
          path = "/taskMgmt/taskHistory"
        }else{
          this.SET_TASKANALYSIS_DETAIL({
            factoryDeptCode:ownedFactory,
            workshopCode:ownedWorkshop,
            lineCode:ownedProductionLine,
            lineId,
            queryType:"workshop",
            queryQcTask,
            taskType,
            status,
            time:time
          });
          path = "/taskMgmt/center"
        }
        this.$router.push({ path: path || "./" })
        .catch(()=>{});
      });
    },
    resize() {
      this.echartsInstance?.resize()
    },

    resetOption(){
      // 指定图表的配置项和数据
      const option = getTaskOption(this.chartData)
      // 使用刚指定的配置项和数据显示图表。
      if (!this.echartsInstance) {
        return
      }
      this.echartsInstance.setOption(option)
      const timer = setTimeout(() => {
        clearTimeout(timer)
        this.resize()
      }, 100);
    },

    changeTab(tab){
      this.activeName = tab;
      this.queryParmas.day = tab;
      this.getTasklList()
      // 清除轮询
      // if (this.refreshTimer) {
      //   clearTimeout(this.refreshTimer);
      //   if(this.echartsInstance){
      //     this.echartsInstance.off('legendselectchanged');
      //   }
      // }
      // this.setRefreshTimer()
    },
  },

  watch:{
    filterData:{
      handler(newVal){
        if(newVal){
          this.queryParmas = Object.assign(this.queryParmas,newVal)
        }
        this.getTasklList()
        // 清除轮询
        if (this.refreshTimer) {
          clearTimeout(this.refreshTimer);
          if(this.echartsInstance){
            this.echartsInstance.off('legendselectchanged');
          }
        }
        this.setRefreshTimer()
      },
      deep: true,
      immediate: true
    }
  },
  beforeDestroy(){
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer);
      if(this.echartsInstance){
        this.echartsInstance.off('legendselectchanged');
      }
    }
  },
  destroyed(){
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer);
      if(this.echartsInstance){
        this.echartsInstance.off('legendselectchanged');
      }
    }
  }
};
</script>
<style lang="scss" scoped>
  .chart-wrap{
    width: 100%;
    height: 300px;
    display: flex;
    align-items: center;
    justify-content:center;
    .chart-content{
      width: 65%;
      height: 100%;
    }
  }
  .query-wrap{
    display: flex;
    align-items: flex-start;
    justify-content:flex-end;
    .button-wrap{
      text-align:right;
      margin-left:16px;
    }
    .seven{
      margin-left:4px;
    }
    .related-me{
      margin-right:8px;
    }
  }

</style>
